package com.ccsu.mymarket.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccsu.mymarket.controller.utils.DataUtils;
import com.ccsu.mymarket.dao.RechargeRecordDao;
import com.ccsu.mymarket.entity.RechargeRecord;
import com.ccsu.mymarket.entity.User;
import com.ccsu.mymarket.service.RechargeService;
import com.ccsu.mymarket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;

@Service
public class RechargeServiceImpl extends ServiceImpl<RechargeRecordDao, RechargeRecord> implements RechargeService {
    private RechargeRecordDao recordDao;
    private UserService userService;

    public RechargeServiceImpl(@Autowired RechargeRecordDao recordDao, @Autowired UserService userService) {
        this.recordDao = recordDao;
        this.userService = userService;
    }

    @Override
    @Transactional
    public boolean addReChargeRecord(Integer id,Double num) {
//        充钱 -> 添加记录,开启事务，保证一致性

        Double purse=userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getId,id).select(User::getPurse)).getPurse();
        purse=purse+num;
        if (userService.update(new LambdaUpdateWrapper<User>()
                .eq(User::getId,id).set(User::getPurse,purse))) {

            RechargeRecord record=new RechargeRecord();
            record.setNum(num);
            record.setAccId(id);
            record.setCreateTime(DataUtils.getDateTime(1));

            this.save(record);
            return true;
        }
        return false;
    }
}
